﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Net.Configuration;
using System.Net.Mail;

using Analysis.DAL;
using Analysis.DAL.Repositories;
using Analysis.Entities;

namespace Analysis.Code
{
    public class Common
    {
        public static void EnumToDropDownList(Type enumType, bool includeAll, DropDownList ddl)
        {
            ddl.Items.Clear();

            var values = Enum.GetValues(enumType);
            if (includeAll)
                ddl.Items.Add(new ListItem("ALL", "ALL"));
            foreach (var itm in values)
            {
                ddl.Items.Add(new ListItem(Enum.GetName(enumType, itm), Enum.GetName(enumType, itm)));
            }
        }

        /// <summary>
        /// Send e-mail via smtp
        /// </summary>
        /// <param name="sendTo">Reciever</param>
        /// <param name="bcc">Reciever hide copy</param>
        /// <param name="subject">Subject</param>
        /// <param name="msgHtml">Message text in html</param>
        public static void SendEmail(string sendTo, string bcc, string subject, string msgHtml, bool sendAsHtml = true)
        {
            SmtpClient client = new SmtpClient();
            //client.EnableSsl = true;

            System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
            SmtpSection smtpSection = (SmtpSection)config.GetSection("system.net/mailSettings/smtp");

            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(smtpSection.Network.UserName);
            msg.To.Add(sendTo);
            if (bcc != "")
                msg.Bcc.Add(bcc);
            msg.Subject = subject;
            msg.IsBodyHtml = sendAsHtml;
            msg.Body = msgHtml;
            client.Send(msg);
        }
        
        public static decimal StringToDecimal(string sValue)
        {
            decimal dOut;

            // try comma
            sValue = sValue.Replace(".", ",");
            if (Decimal.TryParse(sValue, out dOut))
                return dOut;
            else
            {
                // try dot
                sValue = sValue.Replace(",", ".");
                if (Decimal.TryParse(sValue, out dOut))
                    return dOut;
                else
                    throw new FormatException();
            }
        }
    }
}